import config from '@/config'
import { getAccessToken, getRefreshToken, getExpiresTime, setToken, removeToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import {
	toast,
	showConfirm,
	tansParams
} from '@/utils/common'
import { useUserStore } from '@/store/modules/user'
import { showToastAsync } from '@/utils/toast'
import { getReloginStatus, setReloginStatus, showReloginModal } from './auth'

const getStore = () => useUserStore();
let timeout = 10000
const baseUrl = config.baseUrl + config.baseApi;
// 请求白名单，无须token的接口
const whiteList = ['/login', '/refresh-token']

// 是否已经在提示登录过期
let isShowing401Confirm = false

/** 刷新 token */
const refreshTokenRequest = async () => {
	const refreshToken = getRefreshToken()
	if (!refreshToken) {
		throw new Error('RefreshToken 不存在，请重新登录')
	}
	try {
		const res: any = await uni.request({
			method: 'POST',
			url: `${baseUrl}/system/auth/refresh-token?refreshToken=${refreshToken}`,
			dataType: 'json'
		})
		const data =  res.data.data
		if (data?.accessToken && data?.expiresTime) {
			setToken({ accessToken: data.accessToken, refreshToken: data.refreshToken, expiresTime: data.expiresTime })
			return data.accessToken
		} else {
			throw new Error('刷新 Token 失败')
		}
	} catch (error) {
		removeToken()
		throw error
	}
}
/** 主请求函数 */
const request = async (config: any) => {
	console.log('进来了');
	
	// 是否需要设置 token
	let skipToken = (config.headers || {}).skipToken === true
	whiteList.some((v) => {
		if (config.url?.includes(v)) {
			skipToken = true
			return true // 终止遍历
		}
	})

	config.header = config.header || {}

	// ✅ 检查 AccessToken 是否过期
	if (!skipToken) {
		console.log('进来了吗accesstoken');
		
		const expiresTime = getExpiresTime()
		if (!getAccessToken() || (expiresTime && Date.now() >= expiresTime)) {
			console.log('这里进来了吗');
			
			try {
				const newToken = await refreshTokenRequest()
				config.header['Authorization'] = 'Bearer ' + newToken
			} catch (error) {
				// 刷新失败 → 提示重新登录
				if (!getReloginStatus()) {
					setReloginStatus(true)
					showReloginModal()
				}
				return
			}
		} else {
			config.header['Authorization'] = 'Bearer ' + getAccessToken()
		}
	}
   
	

	// if (getAccessToken() && !skipToken) {
	// 	config.header['Authorization'] = 'Bearer ' + getAccessToken()
	// }
	// 设置租户 TODO 芋艿：强制 1 先
	config.header['tenant-id'] = '1'

	// get请求映射params参数
	if (config.params) {
		let url = config.url + '?' + tansParams(config.params)
		url = url.slice(0, -1)
		config.url = url
	}

	try {
		// ✅ 这里直接 await
		const res: any = await uni.request({
			method: config.method || 'get',
			timeout: config.timeout || timeout,
			url: config.baseUrl || baseUrl + config.url,
			data: config.data,
			header: config.header,
			dataType: 'json'
		})

		// 兼容 uni.request 返回 [err, result]
		if (res[0]) {
			toast('后端接口连接异常')
			throw res[0]
		}
       
		 
		const data = res.data // 有的环境是数组，有的是对象
		const code = data.code || 200
		const msg = errorCode[code] || data.msg || errorCode['default']

		if (code === 401) {
			if (!getReloginStatus()) {
				setReloginStatus(true)
				showReloginModal()
			}
			return // ✅ 防止继续执行下面的 code !== 200
		}

		if (code === 500) {
			// toast(msg)
			// throw new Error('500')
			await showToastAsync(msg || '请求失败', 1500, 'none') // ✅ 这里可以直接 await
			throw new Error(msg || '服务器错误')
		}

		if (code !== 200) {
			await showToastAsync(msg || '请求失败', 1500, 'none') // ✅ 这里可以直接 await
			throw new Error(msg || `业务异常 code: ${code}`)
			// throw new Error(code.toString())
		}

		return data
	} catch (error: any) {
		let message = error?.message || ''
		if (message === 'Network Error') {
			message = '后端接口连接异常'
		} else if (message.includes('timeout')) {
			message = '系统接口请求超时'
		} else if (message.includes('Request failed with status code')) {
			message = '系统接口' + message.substr(message.length - 3) + '异常'
		}
		if (message) {
			console.log('message', message);

			// toast(message)
		}
		// throw error
	}
}




// export default request
export default {
	request: request,
	get: async (option: any) => {
		const res: any = await request({
			method: 'GET',
			...option
		})
		return res.data
	},
	post: async (option: any) => {
		const res: any = await request({
			method: 'POST',
			...option
		})
		return res.data
	},
	postOriginal: async (option: any) => {
		const res: any = await request({
			method: 'POST',
			...option
		})
		return res
	},
	delete: async (option: any) => {
		const res: any = await request({
			method: 'DELETE',
			...option
		})
		return res.data
	},
	put: async (option: any) => {
		const res: any = await request({
			method: 'PUT',
			...option
		})
		return res.data
	},
	download: async (option: any) => {
		const res: any = await request({
			method: 'GET',
			responseType: 'blob',
			...option
		})
		return res
	},
	upload: async (option: any) => {
		option.headersType = 'multipart/form-data'
		const res: any = await request({
			method: 'POST',
			...option
		})
		return res
	}
}